package com.gy.bearhelps.help;

import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ListView;

import com.google.gson.reflect.TypeToken;
import com.gy.bearhelps.R;
import com.gy.bearhelps.base.BaseBean;
import com.gy.bearhelps.base.BaseFragment;
import com.gy.bearhelps.help.adapter.HelpHomeAdapter;
import com.gy.bearhelps.help.bean.HelpHomeBean;
import com.gy.bearhelps.help.view.SearchView;
import com.gy.bearhelps.util.AnimUtil;
import com.gy.bearhelps.util.ListViewItemListener;
import com.gy.bearhelps.util.LogUtil;
import com.gy.bearhelps.util.RequestResultListener;
import com.gy.bearhelps.util.Urls;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.RequestParams;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 高岳 on 2016/11/2.
 * Describe:黄页首页
 */
public class HelpHomeFragment extends BaseFragment implements SearchView.SearchViewListener,ListViewItemListener{

    private SearchView searchView;
    private PullToRefreshListView refreshListView,refreshSearchListView;
    private HelpHomeAdapter adapterNormal,adapterSearch;
    private List<HelpHomeBean> mList,normalList,searchList,requestList;
    private int pageStart = 0;
    private boolean isSearch = false;

    @Override
    protected View setView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.fg_help_home,null);
        setTitleMsg("计生黄页");
        return view;
    }

    @Override
    protected void initView() {
        searchView = (SearchView) _rootView.findViewById(R.id.fg_help_searchview);
        refreshListView = (PullToRefreshListView) _rootView.findViewById(R.id.fg_help_listview);
        refreshSearchListView = (PullToRefreshListView) _rootView.findViewById(R.id.fg_help_search_listview);
    }

    @Override
    protected void initData() {
        mList = new ArrayList<>();
        normalList = new ArrayList<>();
        searchList = new ArrayList<>();
        requestList = new ArrayList<>();
        adapterNormal = new HelpHomeAdapter(mContext,normalList);
        adapterSearch = new HelpHomeAdapter(mContext,searchList);
        adapterNormal.setListener(this);
        adapterSearch.setListener(this);

    }

    @Override
    protected void setListener() {
        super.setListener();
        refreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                pageStart = 0;
                showLoadDialog();
                getList();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
            }
        });
        refreshListView.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if(!isLoading && requestList.size() >= Urls.PAGESIZE){
                    isLoading = true;
                    pageStart++;
                    getList();
                }
                finishHandler.sendEmptyMessageDelayed(0,200);
            }
        });
    }

    @Override
    protected void fillData() {
        super.fillData();
        _baseBack.setVisibility(View.INVISIBLE);
        refreshListView.setAdapter(adapterNormal);
        refreshSearchListView.setAdapter(adapterSearch);
        getList();
    }

    @Override
    public void onSearch(String text) {
        LogUtil.e(text);
        searchView.hideKeyboard();
    }

    @Override
    public void onClear() {
        searchList.clear();
        refreshListView.setVisibility(View.VISIBLE);
        refreshSearchListView.setVisibility(View.GONE);
    }

    @Override
    public void doPassActionListener(Object obj, int org1, int org2, String str) {
        switch (org1){
            case 0:
                Intent intent = new Intent(mContext,HelpMapActivity.class);
                if(isSearch){
                    intent.putExtra("endLat",Double.valueOf(searchList.get(org2).latitude));
                    intent.putExtra("endLong",Double.valueOf(searchList.get(org2).longitude));
                    intent.putExtra("address",searchList.get(org2).address+"");
                    intent.putExtra("title",searchList.get(org2).mechanismName+"");
                } else {
                    intent.putExtra("endLat",Double.valueOf(normalList.get(org2).latitude));
                    intent.putExtra("endLong",Double.valueOf(normalList.get(org2).longitude));
                    intent.putExtra("address",normalList.get(org2).address+"");
                    intent.putExtra("title",normalList.get(org2).mechanismName+"");
                }
                startActivity(intent);
                AnimUtil.pushLeftInAndOut(getActivity());
                break;
            case 1:
                String phone = "";
                if(isSearch){
                    phone = searchList.get(org2).telephone;
                } else {
                    phone = normalList.get(org2).telephone;
                }
                Intent intent10 = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone));
                startActivity(intent10);
                break;
        }
    }

    /** 请求黄页列表*/
    public void getList(){
        showLoadDialog();
        RequestParams params = new RequestParams(Urls.select_help_list);
        params.addQueryStringParameter("pageSize",Urls.PAGESIZE+"");
        params.addQueryStringParameter("pageStart",pageStart+"");
        getRequest(params, new RequestResultListener() {
            @Override
            public boolean onSuccess(BaseBean result) {
                finishHandler.sendEmptyMessageDelayed(0,200);
                try {
                    JSONArray array = new JSONArray(result.data);
                    JSONObject obj = array.getJSONObject(0);
                    Type type = new TypeToken<List<HelpHomeBean>>(){}.getType();
                    requestList = gson.fromJson(obj.optString("list"),type);
                    if(pageStart == 0){
                        normalList.clear();
                    }
                    if(requestList.size() > 0){
                        normalList.addAll(requestList);
                        adapterNormal.notifyDataSetChanged();
                    } else {
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return false;
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                finishHandler.sendEmptyMessageDelayed(0,200);
            }
        });
    }

    private Handler finishHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            refreshListView.onRefreshComplete();
        }
    };

}
